<template>
  <VPage>
    <VTable ref="tableRef" v-bind="tableOptins">
      <template #form="{ form }">
        <XForm ref="form" :fieldList="fieldList" :options="formOption" :formData="form" :originOption="originOption" v-if="formShow" />
      </template>
      <template #toolbar_btns>
        <el-button @click="importHandleClick">
          <span class="flex items-center"> <svg-icon icon-class="import" class="mr-[4px]" /> 导出 </span>
        </el-button>

        <div class="ml-auto"></div>
        <FieldSelectBtn :fieldSelectConfig="fieldSelectConfig" @submit="query" />
      </template>
    </VTable>
    <!-- 导出中心 -->
    <DerivedCenter ref="DerivedCenterRef"></DerivedCenter>
  </VPage>
</template>

<script setup lang="jsx">
import { ElMessage, ElMessageBox } from "element-plus"
import XForm from "@/components/XForm/index.vue"
import { onMounted, ref, toRefs } from "vue"
import { inventoryProvisionList } from "@/api/salesInventory"
const tableRef = ref()
import FieldSelectBtn from "@/views/salesInventory/components/FieldSelectBtn.vue"
// 导出中心
import DerivedCenter from "@/components/DerivedCenter"
const DerivedCenterRef = ref()
const importHandleClick = async (e) => {
  let condition = {}
  DerivedCenterRef.value.open({
    tag_name: "performance_indicators",
    condition,
  })
}

// 查询
const query = () => {
  tableRef?.value.query()
}
const formShow = ref(false)
// 枚举 数据
const originOption = ref({})
import { getAloneEnum } from "@/utils/enumUtils"
// 获取下拉数据
onMounted(async () => {
  let oneKeys = ["wmsAttribute", "warehouse", "amazonSite"]
  let optData = await getAloneEnum(oneKeys)
  oneKeys.forEach((key) => {
    originOption.value[key] = optData?.[key]
  })
  originOption.value.amazonSite = originOption.value.amazonSite.map((v) => ({ ...v, value: v.label }))
  setTimeout(() => {
    formShow.value = true
  }, 100)
})

const formOption = ref({ inline: true })
const publicStyle = { style: { width: "200px" } }
const fieldList = ref([
  {
    field: "warehouse_id",
    type: "select",
    originField: "warehouse",
    multiple: true,
    collapseTags: true,
    options: { placeholder: "仓库" },
    ...publicStyle,
  },
  {
    field: "warehouse_attribute",
    type: "select",
    originField: "wmsAttribute",
    multiple: true,
    collapseTags: true,
    options: { placeholder: "仓库属性" },
    ...publicStyle,
  },
  {
    field: "category",
    type: "cascaderNew",
    cascaderType: "category",
    placeholder: "产品品类",
    ...publicStyle,
  },
  {
    field: "owner_id",
    type: "cascaderNew",
    placeholder: "货主",
    cascaderProps: {},
    ...publicStyle,
  },
  {
    field: "department_id",
    type: "cascaderNew",
    cascaderType: "department",
    placeholder: "组织维度",
    cascaderProps: {},
    ...publicStyle,
  },
  {
    field: "country",
    type: "select",
    originField: "amazonSite",
    multiple: true,
    collapseTags: true,
    options: { placeholder: "国家" },
    ...publicStyle,
  },
  {
    field: "month",
    type: "dateTimeRangeNorm",
    itemProps: {
      type: "month",
      format: "YYYY-MM",
      valueFormat: "YYYY-MM",
      shortcuts: [],
      clearable: false,
    },
    ...publicStyle,
    // style: { width: "380px" },
  },
  {
    field: "sku",
    placeholder: "SKU",
    type: "textarea",
    style: { width: "200px" },
  },
])

const configColumns = reactive([
  {
    title: "FBA存货",
    field: "fba",
    align: "center",
    width: 80,
    children: [
      { title: "91-180天", key: "90", children: [] },
      { title: "180-270天", key: "180", children: [] },
      { title: "271-365天", key: "270", children: [] },
      { title: "365以上", key: "365", children: [] },
    ],
  },
  {
    title: "海外仓存货",
    field: "oversea",
    align: "center",
    width: 80,
    children: [
      { title: "121-150天", key: "120", children: [] },
      { title: "151-180天", key: "150", children: [] },
      { title: "181-270天", key: "180", children: [] },
      { title: "365以上", key: "365", children: [] },
    ],
  },
  {
    title: "国内仓存货",
    field: "internal",
    align: "center",
    width: 80,
    children: [{ title: "365以上", key: "365", children: [] }],
  },
])
configColumns.forEach((item) => {
  item.children = item.children.map((v) => ({
    ...v,
    children: [
      { title: "上期计提金额", field: `${item.field}_previous_provision_more_than${v.key}`, fieldShow: `${item.field}_previous_provision_more_than`, width: 110 },
      { title: "本期货存金额", field: `${item.field}_current_inventory_more_than${v.key}`, fieldShow: `${item.field}_current_inventory_more_than`, width: 110 },
      { title: "本期计提金额", field: `${item.field}_current_provision_more_than${v.key}`, fieldShow: `${item.field}_current_provision_more_than`, width: 110 },
      { title: "减值损失", field: `${item.field}_difference_more_than${v.key}`, fieldShow: `${item.field}_difference_more_than`, width: 80 },
    ],
  }))
})

// 列表配置
const tableOptins = reactive({
  formConfig: {
    data: {},
  },
  // tooltipConfig: { showAll: true },
  border: "outer",
  columns: [
    { field: "department_text", title: "一级组织", width: 180 },
    { field: "category_text", title: "一级品类", width: 180 },
    { field: "warehouse_name", title: "仓库", width: 120 },
    { field: "owner_text", title: "货主", width: 100 },
    { field: "asin", title: "asin", width: 100 },
    { field: "seller_sku", title: "渠道SKU", width: 100 },
    { field: "sku", title: "SKU", width: 100 },
  ],
  proxyConfig: {
    ajax: {
      query: ({ page, form }) => {
        let params = {
          page: page.pageNum,
          page_num: page.pageSize,
          ...initForm(form),
          // warehouse_id: 16,
          // warehouse_attribute: 2,
          // category_id: [252],
          // owner_id: [12],
          // department_id: [104],
          // country: ["US"],
          // sku: ["3115342"],
          // month: "2024-03",
        }
        return queryList(params)
      },
    },
  },
  showFooter: true,
  footerMethod({ columns, data }) {
    return [
      columns.map((column, columnIndex) => {
        if ("department_text,category_text,warehouse_name,owner_text,asin,seller_sku,sku".includes(column.field)) {
          return ""
        }
        if (column.field === totalKey.value) {
          return "合计"
        } else {
          return sumNum(data, column.field)
        }
      }),
    ]
  },
})

// 合计
const sumNum = (list, field) => {
  let count = 0
  let fields = field?.split(".")
  let getObjKeys = (data) => {
    return fields.reduce((pre, cur) => pre[cur], data)
  }
  list.forEach((item) => {
    count += Number(getObjKeys(item, fields) || 0)
  })
  return count
}
import { filterColumns } from "@/views/salesInventory/components/method.js"

const totalKey = ref("")
const queryList = async (params) => {
  let columnsData = [...tableOptins.columns, ...configColumns]
  fieldSelectConfig.value.columns = JSON.parse(JSON.stringify(columnsData)).map((v) => {
    if (v?.children) {
      v.children = v.children[0].children
    }
    return v
  })
  const { columns, key } = filterColumns(columnsData, fieldSelectConfig.value.columnsShow)

  totalKey.value = key

  tableRef?.value?.$table.loadColumn(columns)
  return await inventoryProvisionList(params)
}
const fieldSelectConfig = ref({
  save: "inventoryProvision",
  columnsShow: [],
  columns: [],
})
// 组装查询条件
const initForm = (form) => {
  let keys = ["sku"]
  keys.forEach((key) => {
    form[key] = form[key]?.split("\n")?.filter((v) => !!v.trim())
    form[key] = form[key]?.map((v) => v.trim())
  })
  return form
}
</script>
<style lang="scss" scoped>
:deep(.vxe-header--row:nth-child(2)) {
  .vxe-header--column {
    // background: #eff3fe !important;
    background: var(--base-table-hover-bg-color);
  }
}
// :deep(.vxe-body--column) {
//   border-left: 1px solid #e6e7e9;
//   border-bottom: 1px solid #e6e7e9;
// }
// :deep(.vxe-header--column) {
//   border-left: 1px solid #e6e7e9;
//   border-bottom: 1px solid #e6e7e9;
// }
// :deep(.vxe-footer--column) {
//   border-left: 1px solid #e6e7e9;
//   border-bottom: 1px solid #e6e7e9;
// }

:deep(.vxe-body--column) {
  border-left: 1px solid var(--base-link-color);
  border-bottom: 1px solid var(--base-link-color);
}
:deep(.vxe-header--column) {
  border-left: 1px solid var(--base-link-color);
  border-bottom: 1px solid var(--base-link-color);
}
:deep(.vxe-footer--column) {
  border-left: 1px solid var(--base-border-color);
  border-bottom: 1px solid var(--base-border-color);
}
</style>
